<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\UserCollect
 *
 * @method static \Illuminate\Database\Eloquent\Builder|UserCollect newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|UserCollect newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|UserCollect query()
 * @mixin \Eloquent
 * @property int $id
 * @property int $user_id 用户ID
 * @property int $good_id 商品ID
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|UserCollect whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCollect whereGoodId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCollect whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCollect whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserCollect whereUserId($value)
 * @property-read \App\Models\Good|null $goods
 */
class UserCollect extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'user_collects';

    protected $fillable = [
        "user_id","good_id"
    ];


    public static function collect($map){
        $exit = self::query()->where($map)->exists();
        if ($exit){
            $res = self::query()->where($map)->delete();
        }else{
            $res = self::create($map);
        }
        return [
            'code'=>$exit,
            'res'=>$res
        ];
    }

    public function goods(){
        return $this->hasOne(Good::class,"id","good_id");
    }

    /**
     * 获取用户的收藏列表
     * @param $user_id
     * @return array
     */
    public static function getList($user_id){
        $pageSize = request()->input('pageSize',10);
        $list = self::query()
            ->select(['user_collects.*'])
            ->join("goods","goods.id","=","user_collects.good_id")
            ->with(['goods'=>function($query) {
                $query->select(["id","name","image","price"]);
            }])
            ->where("goods.status",0)
            ->where("user_collects.user_id",$user_id)
            ->paginate($pageSize);
        $items = collect($list->items())->toArray();
        foreach ($items as $key=>$item){
            $goods = $item['goods'];
            $items[$key]['goods']['image'] = cdn_url($goods['image']);
        }
        $data['items'] = $items;
        $data['lastPage'] = $list->lastPage();
        $data['total'] = $list->total();
        return $data;
    }

}
